﻿using System;
using System.Speech.Synthesis;

namespace Zero.UControl.Base.Helper
{
    public static class SpeechHelper
    {
        private static readonly SpeechSynthesizer _synthesizer = new SpeechSynthesizer();
        private static bool _isInitialized = false;

        static SpeechHelper()
        {
            Initialize();
        }

        private static void Initialize()
        {
            if (_isInitialized) return;

            _synthesizer.SetOutputToDefaultAudioDevice();
            _synthesizer.Rate = 1;
            _synthesizer.Volume = 50;
            _synthesizer.SelectVoice(GetInstalledVoices()[0]);

            _synthesizer.SpeakCompleted += (s, e) =>
            {
                // 可在这里添加播放完成逻辑
            };

            _isInitialized = true;
        }

        /// <summary>
        /// 播放文本内容（同步方式，会阻塞当前线程）
        /// </summary>
        public static void Speak(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return;
            _synthesizer.Speak(text);
        }

        /// <summary>
        /// 播放文本内容（异步方式，不会阻塞线程）
        /// </summary>
        public static void SpeakAsync(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return;
            _synthesizer.SpeakAsync(text);
        }

        /// <summary>
        /// 停止当前语音播放
        /// </summary>
        public static void Stop()
        {
            _synthesizer.SpeakAsyncCancelAll();
        }

        /// <summary>
        /// 设置语速（范围：-10 到 10）
        /// </summary>
        public static void SetRate(int rate = 1)
        {
            _synthesizer.Rate = Math.Max(-10, Math.Min(10, rate));
        }

        /// <summary>
        /// 设置音量（范围：0 到 100）
        /// </summary>
        public static void SetVolume(int volume = 50)
        {
            _synthesizer.Volume = Math.Max(0, Math.Min(100, volume));
        }

        /// <summary>
        /// 设置使用的语音（可用语音名称参考 GetInstalledVoices）
        /// </summary>
        public static void SelectVoice(string voiceName)
        {
            _synthesizer.SelectVoice(voiceName);
        }

        /// <summary>
        /// 获取所有可用语音名称
        /// </summary>
        public static string[] GetInstalledVoices()
        {
            var voices = _synthesizer.GetInstalledVoices();
            var names = new string[voices.Count];
            for (int i = 0; i < voices.Count; i++)
            {
                names[i] = voices[i].VoiceInfo.Name;
            }
            return names;
        }
    }

}
